package com.hackordie.operations.queries;

import java.util.List;

import com.hackordie.commons.HackOrDieResult;
import com.hackordie.commons.hardware.components.AComponent;
import com.hackordie.constants.EComponentsType;
import com.hackordie.exceptions.HackOrDieException;
import com.hackordie.operations.AHackOrDieOperationComponents;

public class QueryComponents extends AHackOrDieOperationComponents {

	private final String componentName;
	private final EComponentsType componentType;
	private final int first;
	private       int last;
	private final boolean all;
	
	public QueryComponents(String componentName, EComponentsType componentType) {
		super();
		this.componentName = componentName;
		this.componentType = componentType;
		this.first = -1;
		this.last = -1;
		this.all = false;
	}
	
	public QueryComponents() {
	    super();
        this.componentName = "";
        this.componentType = null;
        this.first = -1;
        this.last = -1;
        this.all = true;
    }

    public QueryComponents(int first, int last) {
        this.componentName = "";
        this.componentType = null;
        this.first = first;
        this.last = last;
        this.all = false;
    }

    @Override
	protected boolean checkParameters() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	protected HackOrDieResult executeOperation() throws HackOrDieException {

	    if(all) {
	        result.setObject(getAllComponents());
	    } else {
	        if(first == -1) {	    
	            result.setObject(componentDao.get(componentName, componentType));
	        } else {
	            result.setObject(getAllComponentsByRange());
	        }
	    }
		return result;
	}
	
	private AComponent[] getAllComponents() {
	    List<AComponent> listComponents = componentDao.getAllComponentsList();
	    
	    AComponent[] finalListComponents = new AComponent[listComponents.size()];
        
        for(int i = 0; i < listComponents.size(); i++) {
            finalListComponents[i] = listComponents.get(i);
        }
        
        return finalListComponents;
	}
	
	
	private AComponent[] getAllComponentsByRange() {
	    
	    List<AComponent> listComponents = componentDao.getAllComponentsList();
	    
	    if(first < listComponents.size()) {
	        if(last > listComponents.size()) {
	            last = listComponents.size();
	        }
	        
	        List<AComponent> listComponentsFirtLast = listComponents.subList(first, last);
	        
	        AComponent[] finalListComponents = new AComponent[listComponentsFirtLast.size()];
	        
	        for(int i = 0; i < listComponentsFirtLast.size(); i++) {
	            finalListComponents[i] = listComponentsFirtLast.get(i);
	        }
	        
	        return finalListComponents;
	    }
	    
	    return null;	    
	}
}
